/**
 * lib/pagination
 *
 * @author xiaomi
 */

const PAGE_SIZE = 20;

class Pagination {
    constructor(page_size = PAGE_SIZE, page_num = 1) {
        this.total = 0;
        this.page_num = +page_num || 1;
        this.page_size = +page_size || PAGE_SIZE;
        this.items = [];
    }

    get max_page_num() {
        let max_num = Math.ceil(this.total / this.page_size);

        return max_num;
    }

    setPageNum(page_num, adjust = true) {
        if(adjust) {
            let max_page_num = this.max_page_num;

            page_num = Math.max(1, Math.min(max_page_num, page_num));
        }

        this.page_num = page_num;
    }

    setPageSize(page_size) {
        this.page_size = +page_size || PAGE_SIZE;
    }

    setTotal(total) {
        this.total = +total || 0;
    }

    setItems(items) {
        this.items = items;
    }

    exportHeader() {
        return JSON.stringify({
            num: this.page_num,
            size: this.page_size,
            total: this.total
        });
    }
}

module.exports = Pagination;